import React, { useEffect, useState } from 'react';
import { Card, Checkbox, Tree, Modal, Input, Empty, message } from 'antd';
import { connect, Dispatch } from 'umi';

import { DataNode } from 'rc-tree/lib/interface';
import {
  AllProjectList,
  PortaItem,
  RoleTableListItem,
  IResponse,
} from '../../../type';
import { ConnectState } from '@/models/connect';

import { debounce } from 'lodash';

interface JurisdictionModelProps {
  dispatch: Dispatch;
  allProjectList: Array<AllProjectList>;
  portaList: Array<PortaItem>;
  projectParentList: Array<AllProjectList>;
  modalVisible: boolean;
  onCancel: () => void;
  stepFormValues: RoleTableListItem;
}

import styles from './style.less';

const JurisdictionModel: React.FC<JurisdictionModelProps> = (props) => {
  const {
    allProjectList,
    portaList,
    projectParentList,
    dispatch,
    modalVisible,
    onCancel,
    stepFormValues,
  } = props;

  const [treeSelectId, setTreeSelectId] = useState<number>(); // 选中的项目ID

  const [indeterminate, setIndeterminate] = useState<boolean>(false); // 是否全选中的样式控制
  const [checkAll, setCheckAll] = useState<boolean>(false); // 是否全选
  const [checkedList, setCheckedList] = useState<Array<number>>([]); // 选中的看板ID
  const [plainOptions, setPlainOptions] = useState<Array<PortaItem>>([]); // 看板列表

  const [serachKey, setSerachKey] = useState<string>(''); // 看板搜索关键词

  // 获取树形结构数据
  const treeData: Array<DataNode> = projectParentList
    .map((value: AllProjectList) => {
      const id = value.id;
      const treeData: DataNode = { title: value.name, key: String(id) };
      let children: Array<DataNode> = [];
      allProjectList.map((role: AllProjectList) => {
        if (role.projectId === id) {
          const tree: DataNode = { title: role.name, key: 'add' + String(role.id) }; // 存在父子级相同ID情况，添加 ‘add’ 解决
          children.push(tree);
        }
      });
      if (children.length) {
        treeData.children = children;
      }
      return treeData;
    })
    .filter((v) => v.children);

  // 树形结构节点自定义
  const loop = (data: any) =>
    data.map((item: any) => {
      const { key, title, children } = item;

      if (children) {
        return { title: <span>{title}</span>, key, children: loop(children) };
      }

      return {
        title: <span>{title}</span>,
        key: item.key,
      };
    });

  // 树形结构点击选中
  const selectTree = (e: Array<string>) => {
    setCheckedList([]); // 清除上次选中的看板
    setIndeterminate(false);
    setCheckAll(false);

    const str = e.join();
    if (str.indexOf('add') > -1) {
      // 获取展示的看板
      const portalId = Number(str.replace('add', ''));
      let arr: Array<PortaItem> = [];
      setTreeSelectId(portalId);

      portaList.map((item) => {
        if (item.dashboardPortalId === portalId) {
          arr.push(item);
        }
      });
      setPlainOptions(arr);
    }
  };

  // 全选变化
  const onCheckAllChange = (e: any) => {
    setIndeterminate(false);
    setCheckAll(e.target.checked);
    if (e.target.checked) {
      let arr: Array<number> = [];
      plainOptions.map((v) => {
        arr.push(v.id);
      });
      setCheckedList(arr);
    } else {
      setCheckedList([]);
    }
  };

  // 看板选中变化
  const onChange = (checkedList: Array<any>) => {
    setCheckedList(checkedList);
    setIndeterminate(!!checkedList.length && checkedList.length < plainOptions.length);
    setCheckAll(checkedList.length === plainOptions.length);
  };

  // 看板搜索
  const serach = debounce((value: string) => {
    setCheckedList([]); // 清除上次选中的看板
    setIndeterminate(false);
    setCheckAll(false);

    setSerachKey(value);

    let arr: Array<PortaItem> = [];
    if (!value) { // 当删除关键词后，恢复所有看板显示
      portaList.map((item) => {
        if (item.dashboardPortalId === treeSelectId) {
          arr.push(item);
        }
      });
    } else {
      plainOptions.map((v) => {
        if (v.name.indexOf(value) > -1) {
          arr.push(v);
        }
      });
    }

    setPlainOptions(arr);
  }, 1000);

  // 看板搜索输入框变化
  const onSearchChange = (e: any) => {
    e.persist();
    serach(e.target.value);
  };

  // 提交保存
  const preservation = () => {
    if (checkedList.length === 0) {
      message.warning('请选择需要获得权限的看板');
      return;
    }
    dispatch({
      type: 'role/submitPorta',
      payload: { departmentNos: checkedList, dashboardId: stepFormValues.id },
      callback: (response: IResponse) => {
        const { header } = response;
        if (header.code === 200) {
          message.success('权限设置成功');
        } else {
          message.warning('权限设置失败');
        }
        onCancel();
      },
    });
  };

  useEffect(() => {
    // 获取所有项目列表
    if (allProjectList.length == 0) {
      dispatch({
        type: 'role/fetchAllProject',
      });
    }

    // 获取所有看板列表
    if (portaList.length == 0) {
      dispatch({
        type: 'role/fetchAllPorta',
      });
    }
  }, []);

  return (
    <Modal
      width={1000}
      bodyStyle={{ padding: '32px 40px 48px' }}
      destroyOnClose
      title="权限管理"
      visible={modalVisible}
      onOk={preservation}
      onCancel={() => onCancel()}
    >
      <div className={styles.jurisdictionModel}>
        <Card style={{ width: 350, marginRight: 20 }}>
          <Tree
            onSelect={(e: any) => {
              selectTree(e);
            }}
            treeData={loop(treeData)}
          />
        </Card>
        <Card
          style={{ flex: 1 }}
          title={
            plainOptions.length > 0 || serachKey ? (
              <Input
                placeholder="搜索看板"
                allowClear
                onChange={(e: any) => {
                  onSearchChange(e);
                }}
              />
            ) : (
              ''
            )
          }
        >
          {plainOptions.length > 0 ? (
            <div>
              <div className={styles.checkAll}>
                <Checkbox
                  indeterminate={indeterminate}
                  onChange={onCheckAllChange}
                  checked={checkAll}
                >
                  {plainOptions[0].dashboardPortal.name}
                </Checkbox>
              </div>

              <Checkbox.Group value={checkedList} onChange={onChange}>
                {plainOptions.map((v) => (
                  <Checkbox value={v.id} key={v.id}>
                    {v.name}
                  </Checkbox>
                ))}
              </Checkbox.Group>
            </div>
          ) : (
            <Empty description={serachKey ? '暂无搜索结果' : '请先从左侧选择项目'} />
          )}
        </Card>
      </div>
    </Modal>
  );
};

export default connect(({ role }: ConnectState) => ({
  allProjectList: role.allProjectList || [],
  projectParentList: role.projectParentList || [],
  portaList: role.portaList || [],
}))(JurisdictionModel);
